import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_oss_aliyun/flutter_oss_aliyun.dart';
import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:fusion_one/http/request.dart';
import 'package:intl/intl.dart';

import '../dtos/stsToken.dart';

class OSSUtils {
  static OSSConfig? config;
  static STSToken? token;
  static Future<void> getConfig() async {
    // 获取ossConfig
    var configRes = await DioUtils()
        .get('/configApi/ConfigService/GetResultValue?key=fusionOneOss');
    // 由于json嵌套两层，需要jsonDecode二次解析json
    config = OSSConfig.fromJson(jsonDecode(configRes.resultInfo));
    // 获取stsToken
  }

  static Future<String> getFileToken() async {
    var stsTokenRes = await DioUtils().get(config!.libraryRoot);
    //  map属性转大写
    var map = Map<String, dynamic>.from(stsTokenRes.resultInfo['credentials']);
    var newMap = <String, dynamic>{};
    map.forEach((key, value) {
      newMap[key[0].toUpperCase() + key.substring(1)] = value;
    });
    return jsonEncode(newMap);
  }

  static Future<void> init() async {
    await getConfig();
    Client.init(
        ossEndpoint: config!.remark2,
        bucketName: config!.libraryBucket,
        tokenGetter: getFileToken);
  }
}
